#include "ccarquestorder.h"
#include "socket/protocol/CarChooseClient.h"
#include "socket/protocol/srvordersuccess.h"
#include <QDataStream>
#include <QTcpSocket>

CCarRequestOrder::CCarRequestOrder(QObject *parent)
    : INetWorking(parent)
{
}

CCarRequestOrder::~CCarRequestOrder()
{
}

// refer to srvordersuccess.h
bool CCarRequestOrder::prepareReadData(QTcpSocket *pTcpSocket, protocal::BasePtc *basePtc)
{
    QDataStream in(pTcpSocket);

    if (   basePtc->source != protocal::SERVER\
        || basePtc->srv_command != protocal::SRV_ORDER_SUCCESS\
        || basePtc->size != sizeof(protocal::SrvOrderSuccess)+4*3)
    {
        // TODO: check whether it is necessary to clear the contents of in or pTcpSocket.
        // make an experiment to verify it.
        return false;
    }

    // recieve data, from srvloginans.h
    in >> isSuccess;
    char * tmp = new char[10];
    in >> tmp;
    order_id = QLatin1String(tmp);
    in >> tmp;
    client_name = QLatin1String(tmp);
    delete[] tmp;

    tmp = new char[12];
    in >> tmp;
    client_mobile_num = QLatin1String(tmp);
    delete[] tmp;

    this->formResult();

    return true;
}

void CCarRequestOrder::prepareWriteData(QByteArray *block, void *param)
{
    // we cannot discrete this definition to the outside of the block,
    // and pass the reference to the funtion, or it will cause some
    // unknown problems, such as wrong streams. Maybe it is a bug of QT.
    QDataStream out(block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_3);

    protocal::CCarChooseClient* pCarChooseClient = (protocal::CCarChooseClient*)param;

    // output the head information
    out << (qint32)(pCarChooseClient->source) \
        << (qint32)(pCarChooseClient->srv_command) \
        << (qint32)(pCarChooseClient->size);

    // output the body information

    //
    char * temp = new char [10];
    memcpy(temp, pCarChooseClient->userID, 10);
    out << temp;

    memcpy(temp, pCarChooseClient->carID, 10);
    out << temp;

    delete [] temp;
}

void CCarRequestOrder::formResult()
{
    resultMap.insert(QString("isSuccess"), QString::number(isSuccess));
    resultMap.insert(QString("orderId"), order_id);
    resultMap.insert(QString("clientName"), client_name);
    resultMap.insert(QString("mobileNumber"), client_mobile_num);
}
